"""Command-line sample for the Google Admin Directory API

Simple command-line example for the  Google Admin Directory API
that can print info for a single user, or all users on a domain.

Usage:
  $ python admin_directory.py get user username@your-domain.tld
  $ python admin_directory.py list all-users your-domain.tld

You can also get help on all the command-line flags the program understands
by running:

  $ python admin_directory.py --help

To get detailed log output run:

  $ python admin_directory.py --logging_level=DEBUG

Notes
  
  You'll build a service object by asking for the 'admin' API
  with the 'directory_v1' "version", which is weird.

  This API does not support the OAuth 2.0 service account flow.
  I have used it successfully with the installed app flow.

"""

__author__ = 'jeremy@bat-country.us (Jeremy Ehrhardt)'

from pprint import pprint
import sys
from argparse import ArgumentParser

from oauth2client import client
from apiclient import sample_tools

parser = ArgumentParser(add_help=False)
parser.add_argument('verb', choices={'list', 'get'},
                    help="Action to perform on resource")
parser.add_argument('noun', choices={'user', 'all-users'},
                    help="Resource type to work with")
parser.add_argument('name',
                    help="Name of the individual resource to work with")

actions = {
    ('user',        'get'):     ('users', 'get',    'userKey'),
    ('all-users',   'list'):    ('users', 'list',   'domain'),
}

def make_request(flags):
    """
    Map the verb, noun, name command-line args to a resource method,
    and return something that can execute that request using a service instance.
    """
    action = (flags.noun, flags.verb)
    resource_name, method_name, name_kwarg = actions[action]
    def do_request(service):
        resource = getattr(service, resource_name)()
        request = getattr(resource, method_name)(**{name_kwarg: flags.name})
        return request.execute()
    return do_request

def main(argv):
    service, flags = sample_tools.init(
        argv, 'admin', 'directory_v1', __doc__, __file__,
        # https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
        scope='https://www.googleapis.com/auth/admin.directory.user.readonly',
        parents=[parser])

    try:
        do_request = make_request(flags)
        pprint(do_request(service))

    except client.AccessTokenRefreshError:
        print ('The credentials have been revoked or expired, please re-run'
               'the application to re-authorize')

if __name__ == '__main__':
    main(sys.argv)
